<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容卡片 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <!-- <div style="margin-top: 15px;">
        <el-input placeholder="请输入搜索内容" v-model="input3" class="input-with-search">
          <el-button slot="append" icon="el-icon-search"></el-button>
        </el-input>
        <el-button type="primary">添加用户</el-button>
      </div> -->

      <el-row :gutter="20">
      <el-col :span="7">
        <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" clearable @clear="getUsersList">
           <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
        </el-input>
      </el-col>
      <!-- 添加用户 -->
      <el-col :span="4"><el-button type="primary" @click="dialogaddFormVisible = true">添加用户</el-button></el-col>
      </el-row>
      <!-- 用户表格 -->
      <el-table :data="UsersList" stripe border style="width: 100%">
        <el-table-column type="index" label="#" width="80"></el-table-column>
        <el-table-column prop="username" label="姓名" width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="getUserInfo(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="dialogDeletUserOpen(scope.row)"></el-button>
            <el-tooltip effect="dark" content="修改角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-s-tools" size="mini" @click="setrole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格页码 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalpage">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogaddFormVisible" @close="closeDialog">
      <el-form :model="addUserform" :rules="formrules" ref='adduserFormRef' label-width="70px">
        <el-form-item label="用户名" prop="username">
        <el-input v-model="addUserform.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
        <el-input v-model="addUserform.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
        <el-input v-model="addUserform.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
        <el-input v-model="addUserform.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser" >确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="dialogEditFormVisible" @close="closeeditDialog">
      <el-form :model="editform" :rules="editformrules" ref='editFormRef' label-width="70px">
        <el-form-item label="用户名">
        <el-input v-model="editform.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
        <el-input v-model="editform.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
        <el-input v-model="editform.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogEditFormVisible = false" >取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="roledialogVisible" width="50%" @close="closeRoleDialog">
        <div >当前用户: {{userInfo.username}}</div>
        <div class="margin_top">当前角色：{{userInfo.role_name}}</div>
        <div class="margin_top">分配新角色:
          <el-select v-model="rolevalue" placeholder="请选择">
            <el-option v-for="item in rolelist" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created () {
    this.getUsersList()
  },
  data () {
    // 手机验证规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1(3|4|5|7|8)[0-9]{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确手机号'))
    }
    return {
      rolevalue: '',
      rolelist: [],
      dialogaddFormVisible: false,
      dialogEditFormVisible: false,
      roledialogVisible: false,
      addUserform: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editform: { },
      userInfo: { },
      // 添加用户表单验证规则
      formrules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }]
      },
      // 编辑用户表单验证规则
      editformrules: {
        email: [{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }]
      },
      // 获取用户数据列表参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 页码
      totalpage: 0,
      // 当前页用户数据集合
      UsersList: []
    }
  },
  // { params: this.queryInfo }
  methods: {
    async getUsersList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.totalpage = res.data.total
      this.UsersList = res.data.users
      // console.log(res)
    },
    // 监听页面显示数据条数变化
    handleSizeChange: function (newPage) {
      // console.log(newPage)
      this.queryInfo.pagesize = newPage
      this.getUsersList()
    },
    // 监听当前页面编号变化
    handleCurrentChange: function (currentPage) {
    // console.log(currentPage)
      this.queryInfo.pagenum = currentPage
      this.getUsersList()
    },
    // 监听switch状态改变
    async changeState (temp) {
      // const { data: res } = await this.$http.put('users/' + temp.id + '/state/' + temp.mg_state)
      const { data: res } = await this.$http.put(`users/${temp.id}/state/${temp.mg_state}`)
      if (res.meta.status !== 200) {
        temp.mg_state = !temp.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 添加用户
    addUser: function () {
      this.$refs.adduserFormRef.validate(async vaild => {
        if (!vaild) return
        const { data: res } = await this.$http.post('/users', this.addUserform)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.dialogaddFormVisible = false
        this.getUsersList()
      })
    },
    // 关闭添加用户对话框
    closeDialog: function () {
      this.$refs.adduserFormRef.resetFields()
    },
    // 获取用户信息
    async getUserInfo (userInfo) {
      this.dialogEditFormVisible = true
      // 向服务器请求数据
      const { data: res } = await this.$http.get(`/users/${userInfo.id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editform = res.data
      // 直接使用本地数据 未能及时接收数据变化 安全隐患
      // this.editusername = userInfo.username
      // this.editform.email = userInfo.email
      // this.editform.mobile = userInfo.mobile
    },
    // 关闭编辑信息对话框
    closeeditDialog: function () {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息
    editUserInfo: function () {
      this.$refs.editFormRef.validate(async vaild => {
        if (!vaild) return
        const { data: res } = await this.$http.put(`/users/${this.editform.id}`, { email: this.editform.email, mobile: this.editform.mobile })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.dialogEditFormVisible = false
        // 刷新列表
        this.getUsersList()
        this.$message.success(res.meta.msg)
      })
    },
    // 删除用户
    async dialogDeletUserOpen (userInfo) {
      const data = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (data === 'cancel') {
        return this.$message({ type: 'info', message: '已取消删除' })
      }
      // console.log(data)
      // .then(() => {
      //   this.$message({ type: 'success', message: '删除成功!' })
      // }).catch(() => {
      //   this.$message({ type: 'info', message: '已取消删除' })
      // })
      const { data: res } = await this.$http.delete(`users/${userInfo.id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getUsersList()
      this.$message.success(res.meta.msg)
    },
    // 分配权限
    async setrole (role) {
      this.userInfo = role
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolelist = res.data
      console.log(this.rolelist)
      this.roledialogVisible = true
    },
    // 编辑提交角色
    async submitRole () {
      if (!this.rolevalue) return this.$message.error('请输入新角色')
      console.log(this.userInfo)
      console.log(this.rolevalue)
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.rolevalue })
      // console.log(res)
      this.$message.success(res.meta.msg)
      this.getUsersList()
      this.roledialogVisible = false
    },
    closeRoleDialog: function () {
      this.rolevalue = ''
      this.userInfo = { }
    }
  }
}
</script>
<style lang="less" scoped>
.el-table{
  margin-top: 20px;
  margin-bottom:20px;
  font-size:12px;
}
.footer{
  text-align:center;
  font-size:14px;
  line-height: 40px;
}
.margin_top{
  margin-top:10px;
}
</style>
